import React, { FC, useState, useEffect } from 'react'
import { DownOutlined } from '@ant-design/icons'
import { Button, Col, Form, Input, Row, Select, theme, Space, Table, DatePicker, Spin, Modal, Descriptions } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import qs from 'qs'
import moment from 'moment'
import dayjs from 'dayjs'
import { BASE_URL } from '@/constants'

const { Option } = Select
const QualityList = () => {
  const [pageSize, setPageSize] = useState(10)
  const [pageNum, setPageNum] = useState(1)
  const [pageTotal, setPageTotal] = useState(undefined)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [detailData, setDetailData] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const { token } = theme.useToken()
  const [form] = Form.useForm()
  const [expand, setExpand] = useState(false)
  const [listData, setListData] = useState([])
  useEffect(() => {}, [])
  const handleSearch = (values: any, pageSize: any, pageNum: any) => {
    // 调用数据
    setLoading(true)
    const resValue = {
      ...values,
      date: values['date'] ? values['date'].format('YYYYMMDD') : null,
      size: pageSize, // 当前页面长度
      page: pageNum, // 当前第几页
    }
    fetch(`${BASE_URL}/qmi/lst?${qs.stringify(resValue)}`, {
      method: 'get',
    })
      .then((response) => response.json())
      .then((res) => {
        // setListData([]) // 先将内容清除掉不清楚会出现问题
        setLoading(false)
        if (res.code === 0 && res.data?.info && res.data?.tota) {
          const data = res.data.info
          setListData(data)
          setPageTotal(res.data.tota)
        }
      })
      .catch(() => {
        setListData([])
        setPageTotal(undefined)
        setLoading(false)
      })
  }
  const handleOk = () => {
    setIsModalOpen(false)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const showDetail = (e: any, evid: any, date: any) => {
    e.stopPropagation()
    setIsModalOpen(true)
    fetch(`${BASE_URL}/qmi/dat?${qs.stringify({ evid, date })}`, {
      method: 'get',
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code === 0 && res.data) {
          const data = res.data
          setDetailData(data)
        }
      })
  }
  const columns: ColumnsType<any> = [
    {
      title: '事件号码',
      dataIndex: 'record_evid',
      key: 'record_evid',
      align: 'center',
      width: 100,
    },
    {
      title: '记录时间',
      dataIndex: 'record_time',
      key: 'record_time',
      width: 100,
      render: (value) => moment(value).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a, b) => {
        // 将日期转化成毫秒
        const t1 = new Date(a.record_time).getTime()
        const t2 = new Date(b.record_time).getTime()
        return t1 - t2
      },
      align: 'center',
    },
    {
      title: '请求长度',
      dataIndex: 'access_leng',
      key: 'access_leng',
      width: 100,
      sorter: (a, b) => {
        const t1 = a.access_leng
        const t2 = b.access_leng
        return t1 - t2
      },
      align: 'center',
    },
    {
      title: '来源地址',
      dataIndex: 'access_addr',
      key: 'access_addr',
      align: 'center',
      width: 100,
    },
    {
      title: '请求方法',
      dataIndex: 'access_meth',
      key: 'access_meth',
      align: 'center',
      width: 100,
    },
    {
      title: '请求路径',
      dataIndex: 'access_path',
      key: 'access_path',
      width: 300,
      align: 'center',
    },
    {
      title: '服务地址',
      dataIndex: 'backen_addr',
      key: 'backen_addr',
      align: 'center',
      width: 150,
    },
    {
      title: '服务状态',
      dataIndex: 'backen_code',
      key: 'backen_code',
      align: 'center',
      width: 100,
    },
    {
      title: '服务时长',
      dataIndex: 'backen_time',
      key: 'backen_time',
      align: 'center',
      width: 100,
    },
    {
      title: '响应长度',
      dataIndex: 'return_leng',
      key: 'return_leng',
      width: 100,
      sorter: (a, b) => {
        const t1 = a.return_leng
        const t2 = b.return_leng
        return t1 - t2
      },
      align: 'center',
    },
    {
      title: '响应状态',
      dataIndex: 'return_code',
      key: 'return_code',
      width: 100,
      align: 'center',
    },
    {
      title: '响应时长',
      dataIndex: 'entire_time',
      key: 'entire_time',
      width: 100,
      sorter: (a, b) => {
        const t1 = a.entire_time
        const t2 = b.entire_time
        return t1 - t2
      },
      align: 'center',
    },
    {
      title: '操作',
      key: '操作',
      fixed: 'right',
      width: 100,
      render: (value) => (
        <a onClick={(e) => showDetail(e, value.record_evid, moment(value.record_time).format('YYYYMMDD'))}>详情</a>
      ),
      align: 'center',
    },
  ]
  const handlePageChange = (pageNum: any, pageSize: any) => {
    console.log('handlePageChange', pageNum, pageSize)
    setPageNum(pageNum)
    setPageSize(pageSize)
    handleSearch(form.getFieldsValue(), pageSize, pageNum)
  }
  return (
    <div className="dataListContainer">
      <Form
        form={form}
        name="data_list_search"
        onFinish={(values) => handleSearch(values, pageSize, pageNum)}
        initialValues={{
          orde: 'asc',
          sort: 'record_evid',
          // date: dayjs('2023-06-05', 'YYYY-MM-DD'),
          // size: 10,
          // page: 1,
        }}
      >
        <Row gutter={24}>
          <Col span={6}>
            <Form.Item name="mirt" label="记录起始时间">
              <Input placeholder="记录起始时间" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="mibt" label="服务最小时长">
              <Input placeholder="服务最小时长" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="miet" label="响应最小时长">
              <Input placeholder="响应最小时长" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="mial" label="请求最小长度">
              <Input placeholder="请求最小长度" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="mart" label="记录结束时间">
              <Input placeholder="记录结束时间" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="mabt" label="服务最大时长">
              <Input placeholder="服务最大时长" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="maet" label="响应最大时长">
              <Input placeholder="响应最大时长" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="maal" label="请求最大长度">
              <Input placeholder="请求最大长度" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="mirl" label="响应最小长度">
              <Input placeholder="响应最小长度" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="sort" label="指定排序字段">
              <Select
                placeholder="指定排序字段"
                options={[
                  {
                    value: 'record_evid',
                    label: '事件号码',
                  },
                  {
                    value: 'record_time',
                    label: '记录时间',
                  },
                  {
                    value: 'access_leng',
                    label: '访问长度',
                  },
                  {
                    value: 'backen_time',
                    label: '服务时长',
                  },
                  {
                    value: 'return_leng',
                    label: '响应长度',
                  },
                  {
                    value: 'entire_time',
                    label: '响应时长',
                  },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="date" label="查询日期">
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>

          <Col span={6}>
            <Form.Item name="addr" label="来源地址">
              <Input placeholder="来源地址" />
            </Form.Item>
          </Col>

          <Col span={6}>
            <Form.Item name="marl" label="响应最大长度">
              <Input placeholder="响应最大长度" type="number" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="orde" label="指定升序降序">
              <Select
                placeholder="指定升序降序"
                options={[
                  {
                    value: 'asc',
                    label: '升序',
                  },
                  {
                    value: 'desc',
                    label: '降序',
                  },
                ]}
              />
            </Form.Item>
          </Col>
        </Row>
        <div style={{ textAlign: 'right' }}>
          <Space size="small">
            <Button type="primary" htmlType="submit" disabled={loading}>
              查询
            </Button>
            <Button
              onClick={() => {
                form.resetFields()
                setListData([]) // 是否可以直接将数据清空
                setPageTotal(undefined)
              }}
            >
              清空
            </Button>
          </Space>
        </div>
      </Form>
      <Spin spinning={loading}>
        <div
          className="list"
          style={{
            textAlign: 'center',
            background: token.colorFillAlter,
            borderRadius: token.borderRadiusLG,
            marginTop: 16,
          }}
        >
          <Table
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              onChange: handlePageChange,
              total: pageTotal,
            }}
            size="small"
            columns={columns}
            dataSource={listData}
            scroll={{ x: 1300 }}
          />
        </div>
      </Spin>
      <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Descriptions layout="vertical" title="响应数据详情" column={2}>
          <Descriptions.Item label="记录时间">
            {moment(detailData?.record_time).format('YYYY-MM-DD HH:mm:ss')}
          </Descriptions.Item>
          <Descriptions.Item label="请求长度">{detailData?.access_leng}</Descriptions.Item>
          <Descriptions.Item label="请求地址">{detailData?.access_addr}</Descriptions.Item>
          <Descriptions.Item label="请求方法">{detailData?.access_meth}</Descriptions.Item>
          <Descriptions.Item label="请求路径">{detailData?.access_path}</Descriptions.Item>
          <Descriptions.Item label="响应主机">{detailData?.backen_addr}</Descriptions.Item>
          <Descriptions.Item label="响应状态">{detailData?.backen_code}</Descriptions.Item>
          <Descriptions.Item label="响应时延">{detailData?.backen_time}</Descriptions.Item>
          <Descriptions.Item label="响应长度">{detailData?.return_leng}</Descriptions.Item>
          <Descriptions.Item label="返回状态">{detailData?.return_code}</Descriptions.Item>
          <Descriptions.Item label="返回时延">{detailData?.entire_time}</Descriptions.Item>
          <Descriptions.Item label="参数代理">{detailData?.req_arg_xff}</Descriptions.Item>
        </Descriptions>
      </Modal>
    </div>
  )
}
export default QualityList
